In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem.
Most computer programming languages support recursion by allowing a function to call itself from within its own code. Some functional programming languages (for instance, Clojure) do not define any built-in looping constructs, and instead rely solely on recursion. It is proved in computability theory that these recursion-only languages are Turing complete; this means that they are as powerful (they can be used to solve the same problems) as imperative languages based on control structures such as and .
Repeatedly calling a function from within itself may cause the call stack to have a size equal to the sum of the input sizes of all involved calls. It follows that, for problems that can be solved easily by iteration, recursion is generally less efficient, and, for certain problems, algorithmic or compiler-optimization techniques such as tail call optimization may improve computational performance over a naive recursive implementation.
John McCarthy took the first steps by creating the programming language LISP in 1960. In his paper Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I, McCarthy showed that recursion could be core in a programming language that works with symbols by processing them step by step. In LISP, recursion could be used in functions using simple rules, and there was also a way to evaluate them in the language. This demonstrated that recursion was a practical way to write programs and that it also describes the process of computation. Therefore, LISP became one of the first programming languages to use recursion as a main feature, and later on also influenced other languages that followed.
During that time, recursion was also added to ALGOL 60. The Report on the Algorithmic Language ALGOL 60, which was published in 1960, was the outcome of an international attempt at designing a standard language. Allowing procedures to call themselves was one of the new important features of the language. Before that, only loops were allowed to be used by programmers, so it was a significant change. Recursion allowed programmers to describe algorithms in a more natural and flexible way.
An example is computing the factorial of an integer n, which is the product of all integers from 0 to n. For this problem, the definition 0! = 1 is a base case. Without it, the recursion may continue indefinitely, leading to non-termination or even stack overflow errors in actual implementations.
Designing a correct base case is crucial for both theoretical and practical reasons. Some problems have a natural base case (e.g., the empty list is a base case in some recursive list-processing functions), while others require an additional parameter to provide a stopping criterion (e.g., using a depth counter in recursive tree traversal).
In recursive computer programming, omitting the base case or defining it incorrectly may result in unintended infinite recursion. In a study, researchers showed that many students struggle to identify appropriate base cases.
In the factorial example, the recursive case is defined as: Here, each invocation of the function decreases the input by 1. Thus, it ensures that the recursion eventually reaches the base case of .
The recursive case is analogous to the inductive step in a proof by induction: it assumes that the function works for a smaller instance and then extends this assumption to the current input. Recursive definitions and algorithms thus closely parallel inductive arguments in mathematics, and their correctness often relies on similar reasoning techniques.
The code above specifies a list of strings to be either empty, or a structure that contains a string and a list of strings. The self-reference in the definition permits the construction of lists of any (finite) number of strings.
Another example of inductive definition is the natural numbers (or positive integers):
A natural number is either 1 or n+1, where n is a natural number.
Similarly, recursive grammars are often used to model the structure of expressions and statements in programming languages. Language designers often express in a syntax such as Backus–Naur form; here is such a grammar, for a simple language of arithmetic expressions with multiplication and addition:
This says that an expression is either a number, a product of two expressions, or a sum of two expressions. By recursively referring to expressions in the second and third lines, the grammar permits arbitrarily complicated arithmetic expressions such as (5 * ((3 * 6) + 8)), with more than one product or sum operation in a single expression.
A coinductive definition of infinite streams of strings, given informally, might look like this:
A stream of strings is an object s such that:
head(s) is a string, and
tail(s) is a stream of strings.
This is very similar to an inductive definition of lists of strings; the difference is that this definition specifies how to access the contents of the data structure—namely, via the accessor functions head and tail—and what those contents may be, whereas the inductive definition specifies how to create the structure and what it may be created from.
Corecursion is related to coinduction, and can be used to compute particular instances of (possibly) infinite objects. As a programming technique, it is used most often in the context of lazy evaluation programming languages, and can be preferable to recursion when the desired size or precision of a program's output is unknown. In such cases the program requires both a definition for an infinitely large (or infinitely precise) result, and a mechanism for taking a finite portion of that result. The problem of computing the first n prime numbers is one that can be solved with a corecursive program (e.g. here).
Single recursion is often much more efficient than multiple recursion, and can generally be replaced by an iterative computation, running in linear time and requiring constant space. Multiple recursion, by contrast, may require exponential time and space, and is more fundamentally recursive, not being able to be replaced by iteration without an explicit stack.
Multiple recursion can sometimes be converted to single recursion (and, if desired, thence to iteration). For example, while computing the Fibonacci sequence naively entails multiple iteration, as each value requires two previous values, it can be computed by single recursion by passing two successive values as parameters.
Indirect recursion is also called mutual recursion, which is a more symmetric term, though this is simply a difference of emphasis, not a different notion. That is, if f calls g and then g calls f, which in turn calls g again, from the point of view of f alone, f is indirectly recursing, while from the point of view of g alone, it is indirectly recursing, while from the point of view of both, f and g are mutually recursing on each other. Similarly a set of three or more functions that call each other can be called a set of mutually recursive functions.
Thus, the defining characteristic of a structurally recursive function is that the argument to each recursive call is the content of a field of the original input. Structural recursion includes nearly all tree traversals, including XML processing, binary tree creation and search, etc. By considering the algebraic structure of the natural numbers (that is, a natural number is either zero or the successor of a natural number), functions such as factorial may also be regarded as structural recursion.
is the alternative:
This distinction is important in proving termination of a function.
On the basis of elegance, wrapper functions are generally approved, while short-circuiting the base case is frowned upon, particularly in academia. Hybrid algorithms are often used for efficiency, to reduce the overhead of recursion in small cases, and arm's-length recursion is a special case of this.
Wrapper functions can be used to validate parameters (so the recursive function can skip these), perform initialization (allocate memory, initialize variables), particularly for auxiliary variables such as "level of recursion" or partial computations for memoization, and handle exceptions and errors. In languages that support , the auxiliary function can be nested inside the wrapper function and use a shared scope. In the absence of nested functions, auxiliary functions are instead a separate function, if possible private (as they are not called directly), and information is shared with the wrapper function by using pass-by-reference.
| + vs. short-circuit | |
if (n <= 0) {
return 1;
} else {
return fac1(n - 1) * n;
}
}
| // assert(n >= 2);
if (n == 2) {
return 2;
} else {
return fac2(n - 1) * n;
}
}
int fac2wrapper(int n) {
if (n <= 1) {
return 1;
} else {
return fac2(n);
}
}
|
Short-circuiting is primarily a concern when many base cases are encountered, such as Null pointers in a tree, which can be linear in the number of function calls, hence significant savings for algorithms; this is illustrated below for a depth-first search. Short-circuiting on a tree corresponds to considering a leaf (non-empty node with no children) as the base case, rather than considering an empty node as the base case. If there is only a single base case, such as in computing the factorial, short-circuiting provides only savings.
Conceptually, short-circuiting can be considered to either have the same base case and recursive step, checking the base case only before the recursion, or it can be considered to have a different base case (one step removed from standard base case) and a more complex recursive step, namely "check valid then recurse", as in considering leaf nodes rather than Null nodes as base cases in a tree. Because short-circuiting has a more complicated flow, compared with the clear separation of base case and recursive step in standard recursion, it is often considered poor style, particularly in academia.
The standard recursive algorithm for a DFS is:
In terms of the standard steps, this moves the base case check before the recursive step. Alternatively, these can be considered a different form of base case and recursive step, respectively. Note that this requires a wrapper function to handle the case when the tree itself is empty (root node is Null).
In the case of a perfect binary tree of height h, there are 2 h+1−1 nodes and 2 h+1 Null pointers as children (2 for each of the 2 h leaves), so short-circuiting cuts the number of function calls in half in the worst case.
In C, the standard recursive algorithm may be implemented as:
if (!node) {
return false; // base case
} else if (node->data == i) {
return true;
} else {
return tree_contains(node->left, i)
|| tree_contains(node->right, i);
}
}
The short-circuited algorithm may be implemented as:
// Wrapper function to handle empty tree
bool tree_contains(struct BinaryTree* node, int i) {
// Assumes node != NULL
bool tree_contains_aux(struct BinaryTree* node, int i) {
if (!node) {
return false; // empty tree
} else {
return tree_contains_aux(node, i); // call auxiliary function
}
}
assert(node);
if (node->data == i) {
return true; // found
} else {
// recurse
return (node->left && tree_contains_aux(node->left, i))
|| (node->right && tree_contains_aux(node->right, i));
}
}
Note the use of short-circuit evaluation of the Boolean && (AND) operators, so that the recursive call is made only if the node is valid (non-Null). Note that while the first term in the AND is a pointer to a node, the second term is a Boolean, so the overall expression evaluates to a Boolean. This is a common idiom in recursive short-circuiting. This is in addition to the short-circuit evaluation of the Boolean || (OR) operator, to only check the right child if the left child fails. In fact, the entire control flow of these functions can be replaced with a single Boolean expression in a return statement, but legibility suffers at no benefit to efficiency.
Compare the templates to compute xn defined by xn = f(n, xn-1) from xbase:
'''function''' recursive(n)
'''if''' n == base
'''return''' xbase
'''else'''
'''return''' f(n, recursive(n - 1))
| '''function''' iterative(n)
x = xbase
'''for''' i = base + 1 to n
x = f(i, x)
'''return''' x
|
For an imperative language the overhead is to define the function, and for a functional language the overhead is to define the accumulator variable x.
For example, a factorial function may be implemented iteratively in C by assigning to a loop index variable and accumulator variable, rather than by passing arguments and returning values by recursion:
unsigned int product = 1; // empty product is 1
while (n > 0) {
product *= n;
--n;
}
return product;
}
Conversely, all iterative functions and procedures that can be evaluated by a computer (see Turing completeness) can be expressed in terms of recursive functions; iterative control constructs such as and are routinely rewritten in recursive form in functional languages. However, in practice this rewriting depends on tail call elimination, which is not a feature of all languages. C, Java, and Python are notable mainstream languages in which all function calls, including , may cause stack allocation that would not occur with the use of looping constructs; in these languages, a working iterative program rewritten in recursive form may stack overflow, although tail call elimination may be a feature that is not covered by a language's specification, and different implementations of the same language may differ in tail call elimination capabilities.
As a concrete example, the difference in performance between recursive and iterative implementations of the "factorial" example above depends highly on the compiler used. In languages where looping constructs are preferred, the iterative version may be as much as several orders of magnitude faster than the recursive one. In functional languages, the overall time difference of the two implementations may be negligible; in fact, the cost of multiplying the larger numbers first rather than the smaller numbers (which the iterative version given here happens to do) may overwhelm any time saved by choosing iteration.
* @brief computes GCD using Euclidean algorithm
* @param x an int
* @param y an int, such that x >= y >= 0
* @returns the GCD of x and y
*/
int gcd(int x, int y) {
if (y == 0) {
return x;
} else {
return gcd(y, x % y);
}
}
| * @brief computes the factorial of a non-negative integer
* @param n an int
* @returns the factorial of n
*/
unsigned int factorial(unsigned int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
|
The significance of tail recursion is that when making a tail-recursive call (or any tail call), the caller's return position need not be saved on the call stack; when the recursive call returns, it will branch directly on the previously saved return position. Therefore, in languages that recognize this property of tail calls, tail recursion saves both space and time.
void recursiveFunction(int num) {
printf("%d\n", num);
if (num < 4) {
recursiveFunction(num + 1);
}
}
void recursiveFunction(int num) {
if (num < 4) {
recursiveFunction(num + 1);
}
printf("%d\n", num);
}
The output of function 2 is that of function 1 with the lines swapped.
In the case of a function calling itself only once, instructions placed before the recursive call are executed once per recursion before any of the instructions placed after the recursive call. The latter are executed repeatedly after the maximum recursion has been reached.
Also note that the order of the print statements is reversed, which is due to the way the functions and statements are stored on the call stack.
\begin{cases}
1 & \mbox{if } n = 0 \\
n \cdot \operatorname{fact}(n-1) & \mbox{if } n > 0 \\
\end{cases}
'''function''' factorial is: |
The function can also be written as a recurrence relation:
b4 = 4 × b3
= 4 × (3 × b2)
= 4 × (3 × (2 × b1))
= 4 × (3 × (2 × (1 × b0)))
= 4 × (3 × (2 × (1 × 1)))
= 4 × (3 × (2 × 1))
= 4 × (3 × 2)
= 4 × 6
= 24
|
This factorial function can also be described without using recursion by making use of the typical looping constructs found in imperative programming languages:
'''function''' factorial is: |
The imperative code above is equivalent to this mathematical definition using an accumulator variable :
t & \mbox{if } n = 0 \\
\operatorname{fact_{acc}}(n-1, nt) & \mbox{if } n > 0 \\
\end{cases}
\end{align}
The definition above translates straightforwardly to functional programming languages such as Scheme; this is an example of iteration implemented recursively.
Function definition:
\begin{cases}
x & \mbox{if } y = 0 \\
\gcd(y, \operatorname{remainder}(x,y)) & \mbox{if } y > 0 \\
\end{cases}
'''function''' gcd is:
'''input''': integer ''x'', integer ''y'' such that ''x'' > 0 and ''y'' >= 0
|
Recurrence relation for greatest common divisor, where expresses the remainder of :
gcd(27, 9) = gcd(9, 27% 9)
= gcd(9, 0)
= 9
|
gcd(111, 259) = gcd(259, 111% 259)
= gcd(259, 111)
= gcd(111, 259% 111)
= gcd(111, 37)
= gcd(37, 111% 37)
= gcd(37, 0)
= 37
|
The recursive program above is tail-recursive; it is equivalent to an iterative algorithm, and the computation shown above shows the steps of evaluation that would be performed by a language that eliminates tail calls. Below is a version of the same algorithm using explicit iteration, suitable for a language that does not eliminate tail calls. By maintaining its state entirely in the variables x and y and using a looping construct, the program avoids making recursive calls and growing the call stack.
'''function''' gcd is: |
The iterative algorithm requires a temporary variable, and even given knowledge of the Euclidean algorithm it is more difficult to understand the process by simple inspection, although the two algorithms are very similar in their steps.
Function definition:
\begin{cases}
1 & \mbox{if } n = 1 \\
2\cdot\operatorname{hanoi}(n-1) + 1 & \mbox{if } n > 1\\
\end{cases}
Recurrence relation for hanoi:
hanoi(4) = 2×hanoi(3) + 1
= 2×(2×hanoi(2) + 1) + 1
= 2×(2×(2×hanoi(1) + 1) + 1) + 1
= 2×(2×(2×1 + 1) + 1) + 1
= 2×(2×(3) + 1) + 1
= 2×(7) + 1
= 15
|
Example implementations:
'''function''' hanoi is: |
Although not all recursive functions have an explicit solution, the Tower of Hanoi sequence can be reduced to an explicit formula.
h1 = 1 = 21 - 1
h2 = 3 = 22 - 1
h3 = 7 = 23 - 1
h4 = 15 = 24 - 1
h5 = 31 = 25 - 1
h6 = 63 = 26 - 1
h7 = 127 = 27 - 1
In general:
hn = 2n - 1, for all n >= 1
|
Recursion is used in this algorithm because with each pass a new array is created by cutting the old one in half. The binary search procedure is then called recursively, this time on the new (and smaller) array. Typically the array's size is adjusted by manipulating a beginning and ending index. The algorithm exhibits a logarithmic order of growth because it essentially divides the problem domain in half with each pass.
Example implementation of binary search in C:
/**
* @brief Call binary_search with proper initial conditions.
* @param data an array of integers SORTED in ASCENDING order
* @param target the integer to search for
* @param count the total number of elements in the array
* @returns result of binary_search
*/
int search(int data, int target, int count) {
// Start = 0 (beginning index)
// End = count - 1 (top index)
return binary_search(data, target, 0, count - 1);
}
* @brief Binary Search Algorithm.
* @param data an array of integers SORTED in ASCENDING order
* @param target the integer to search for
* @param start the minimum array index
* @param end the maximum array index
* @returns position of the integer toFind within array data, -1 if not found
*/
int binary_search(int data, int target, int start, int end) {
//Get the midpoint.
int mid = start + (end - start) / 2; //Integer division
if (start > end) {
return -1; // Stop condition (base case)
} else if (data[mid] == target) {
return mid; // Found, return index
} else if (data[mid] > target) {
// Data is greater than target, search lower half
return binary_search(data, target, start, mid - 1);
} else {
// Data is less than target, search upper half
return binary_search(data, target, mid + 1, end);
}
}
"Recursive algorithms are particularly appropriate when the underlying problem or the data to be treated are defined in recursive terms."
The examples in this section illustrate what is known as "structural recursion". This term refers to the fact that the recursive procedures are acting on data that is defined recursively.
As long as a programmer derives the template from a data definition, functions employ structural recursion. That is, the recursions in a function's body consume some immediate piece of a given compound value.
int data; // some integer data
struct LinkedList* next; // pointer to another node of the linked list
};
Because the struct node data structure is defined recursively, procedures that operate on it can be implemented naturally as recursive procedures. The list_print procedure defined below walks down the list until the list is empty (i.e., the list pointer has a value of NULL). For each node it prints the data element (an integer). In the C implementation, the list remains unchanged by the list_print procedure.
// base case
if (list) {
printf("%d ", list->data); // print integer data followed by a space
list_print(list->next); // recursive call on the next node
}
}
int data; // some integer data
struct BinaryTree* left; // pointer to the left subtree
struct BinaryTree* right; // pointer to the right subtree
};
Operations on the tree can be implemented using recursion. Note that because there are two self-referencing pointers (left and right), tree operations may require two recursive calls:
if (!node) {
return 0; // base case
} else if (node->data == i) {
return 1;
} else {
return tree_contains(node->left, i) || tree_contains(node->right, i);
}
}
// base case
if (node) {
tree_print(node->left); // go left
printf("%d ", node->data); // print the integer followed by a space
tree_print(node->right); // go right
}
}
The above example illustrates an Tree traversal of the binary tree. A Binary search tree is a special case of the binary tree where the data elements of each node are in order.
import java.io.File;
public class Example {
/**
* Obtains the filesystem roots
* Proceeds with the recursive filesystem traversal
*/
private static void traverse() {
File[] fs = File.listRoots();
for (int i = 0; i < fs.length; i++) {
System.out.println(fs[i]);
if (fs[i].isDirectory() && fs[i].canRead()) {
rtraverse(fs[i]);
}
}
}
/**
* Recursively traverse a given directory
*
* @param fd indicates the starting point of traversal
*/
private static void rtraverse(File fd) {
File[] fss = fd.listFiles();
for (int i = 0; i < fss.length; i++) {
System.out.println(fss[i]);
if (fss[i].isDirectory() && fss[i].canRead()) {
rtraverse(fss[i]);
}
}
}
public static void main(String[] args) {
traverse();
}
}
This code is both recursion and iteration - the files and directories are iterated, and each directory is opened recursively.
The "rtraverse" method is an example of direct recursion, whilst the "traverse" method is a wrapper function.
The "base case" scenario is that there will always be a fixed number of files and/or directories in a given filesystem.
Then the Big O of the time-complexity is thus:
where represents the number of recursive calls at each level of recursion, represents by what factor smaller the input is for the next level of recursion (i.e. the number of pieces you divide the problem into), and represents the work that the function does independently of any recursion (e.g. partitioning, recombining) at each level of recursion.
define a procedure, which can be used to search for a path from X to Y, either by finding a direct arc from X to Y, or by finding an arc from X to Z, and then searching recursively for a path from Z to Y. Prolog executes the procedure by reasoning top-down (or backwards) and searching the space of possible paths depth-first, one branch at a time. If it tries the second clause, and finitely fails to find a path from Z to Y, it backtracks and tries to find an arc from X to another node, and then searches for a path from that other node to Y.
However, in the logical reading of logic programs, clauses are understood declaratively as universally quantified conditionals. For example, the recursive clause of the path-finding procedure is understood as representing the knowledge that, for every X, Y and Z, if there is an arc from X to Z and a path from Z to Y then there is a path from X to Y. In symbolic form:
The logical reading frees the reader from needing to know how the clause is used to solve problems. The clause can be used top-down, as in Prolog, to reduce problems to subproblems. Or it can be used bottom-up (or forward chaining), as in Datalog, to derive conclusions from conditions. This separation of concerns is a form of abstraction, which separates declarative knowledge from problem solving methods (see Algorithm#Algorithm = Logic + Control).
Below is a Java code that would use infinite recursion:
static void recursive() {
// Recursive function with no way out
recursive();
}
public static void main(String[] args) {
recursive(); // Executes the recursive function upon runtime
}
}
|
|